var IsDealInfoDlg = {isDealInfoData: {}, zTreeInstance: null, validateFields: {}};
var windowNameIndex = parent.layer.getFrameIndex(window.name);
IsDealInfoDlg.clearData = function () {
    this.isDealInfoData = {};
};
IsDealInfoDlg.set = function (key, val) {
    this.isDealInfoData[key] = (typeof value == "undefined") ? $("#" + key).val() : value;
    return this;
};
IsDealInfoDlg.get = function (key) {
    return $("#" + key).val();
};
IsDealInfoDlg.close = function () {
    parent.layer.close(windowNameIndex);
};
IsDealInfoDlg.showIsDealSelectTree = function () {
    var pName = $("#pName");
    var pNameOffset = $("#pName").offset();
    $("#parentIsDealMenu").css({
        left: pNameOffset.left + "px",
        top: pNameOffset.top + pName.outerHeight() + "px"
    }).slideDown("fast");
    $("body").bind("mousedown", onBodyDown)
};
IsDealInfoDlg.hideIsDealSelectTree = function () {
    $("#parentIsDealMenu").fadeOut("fast");
    $("body").unbind("mousedown", onBodyDown)
};
IsDealInfoDlg.resetSearch = function () {
    $("#payServiceNames").val("");
    $("#payServicePrices").val("")
};
IsDealInfoDlg.collectData = function () {
    this.set('reservationsId').set('consumptionStatus').set('followStatus').set('appointmentTime').set('arrearsRemarks').set('arrears').set('serviceActualPay').set('doctor').set('nurse').set('customerId').set('operationTime').set('noDealCause').set('appointmentTimes').set('toVoidCause').set('payServiceId').set('reservationss').set('payServiceNum').set('remarkss').set('reservations').set('remarks')
};
IsDealInfoDlg.validate = function () {
    $('#isDealInfoForm').data("bootstrapValidator").resetForm();
    $('#isDealInfoForm').bootstrapValidator('validate');
    return $("#isDealInfoForm").data('bootstrapValidator').isValid()
};

function onBodyDown(event) {
    if (!(event.target.id == "menuBtn" || event.target.id == "parentIsDealMenu" || $(event.target).parents("#parentIsDealMenu").length > 0)) {
        IsDealInfoDlg.hideIsDealSelectTree()
    }
}

var getCount = 0;

function checkIsYesterdayCust() {
    var arrivalTime = $("#arrivalTimeStr").val();
    var now = new Date();
    var time = now.getFullYear() + "-" + ((now.getMonth() + 1) < 10 ? "0" : "") + (now.getMonth() + 1) + "-" + (now.getDate() < 10 ? "0" : "") + now.getDate();
    if (arrivalTime.indexOf(time) >= 0) {
        return true;
    } else {
        return false;
    }
}

var count = 0;
IsDealInfoDlg.openBillNew = function () {
    var currentSeat = parent.parent.$('#currentSeat').html();  //选定界面
    var intamount = 0;
    var lowestPriceBill = $('#lowestPriceBill').val();
    $("#projectListInfo .amount").each(function (index, obj) {
        if (parseFloat($(obj).parent().parent().find(".unitPriceOne").val()) != parseFloat($(obj).parent().parent().find(".unitPriceTwo").val())) {
            if (parseFloat($(obj).val()) < parseFloat($(obj).parent().parent().find(".unitPriceOne").val() * $(obj).parent().parent().find(".num").val())) {
                intamount++;
            }
        }
    });
    if (checkIsYesterdayCust()) {
        var des = $("#proRemark").val();
        var remarks = des.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(/\s/g, ' ');
        var customerId = $('#customerId').val();
        var reservationsIdx = $('#reservationsIdx').val();
        var reservationsId = $("#reservationsId").val();
        if ($('#integral').is(':checked') || $('#earnest').is(':checked')) {
            var dataList = $(".deductionDealList");
            var billList = [];
            if ($('#integral').is(':checked') && $('#earnest').is(':checked')) {
                var newTotalSum = $("#newTotalSum").val();
                var newPayAmount = $("#newPayAmount").val();
                var jfAmount = 0;
                var earnestAmount = 0;
                var jfBalance = parseFloat($("#jfbalance").html());
                var moneyBalance = parseFloat($("#moneyBalance").html());
                if (newTotalSum != newPayAmount) {
                    for (var i = 0; i < dataList.length; i++) {
                        var obj = dataList[i];
                        var dealInfo = {};
                        dealInfo.reservationsIdx = reservationsIdx;
                        var treatmentUnit = $("#treatmentUnitHtml").html();
                        dealInfo.customerId = customerId;
                        dealInfo.reservationsId = reservationsId;
                        dealInfo.remarks = remarks;
                        dealInfo.payServiceId = $(obj).find(".payServiceId").val();
                        dealInfo.vipPayserviceId = $(obj).find(".vipPayserviceId").val();
                        dealInfo.payServiceNum = parseFloat($(obj).find(".num").html());
                        var payServiceNum = parseFloat($(obj).find(".num").html());
                        var doctor = $(obj).find(".doctor").val();
                        var nurse = $("#projectNurse").val();
                        if (payServiceNum < 1) {
                            layer.msg('请输入项目数量！', {time: 1000, icon: 2});
                            count = 0;
                            return false;
                        }
                        if ((doctor == null || doctor == "") && (nurse == null || nurse == "")) {
                            layer.msg('请选择医生或护士！', {time: 1000, icon: 2});
                            count = 0;
                            return false;
                        }
                        if ("洁牙" == treatmentUnit) {
                            dealInfo.dentalHygienist = $(obj).find(".doctor").val();
                        } else {
                            dealInfo.dentalHygienist = "";
                        }
                        dealInfo.foldingPay = parseFloat($(obj).find(".amount").html());
                        dealInfo.doctor = $(obj).find(".doctor").val();
                        dealInfo.nurse = $("#projectNurse").val();
                        dealInfo.leftUp = $(obj).find(".leftUp").val();
                        dealInfo.leftDown = $(obj).find(".leftDown").val();
                        dealInfo.rightUp = $(obj).find(".rightUp").val();
                        dealInfo.rightDown = $(obj).find(".rightDown").val();
                        dealInfo.deductionType = parseFloat($(obj).find(".deductionType").val());
                        var deductionType = $(obj).find(".deductionType").find("option:selected").text();
                        if (deductionType.indexOf("返现") >= 0) {
                            jfAmount = jfAmount + parseFloat($(obj).find(".deductionAmount").val())
                        }
                        earnestAmount = earnestAmount + parseFloat($(obj).find(".depositAmount").val());
                        dealInfo.deductionTypeName = parseFloat($(obj).find(".deductionType").html());
                        dealInfo.deductionAmount = parseFloat($(obj).find(".deductionAmount").val());
                        dealInfo.orderDiscount = parseFloat($(obj).find(".orderDiscount").val());
                        dealInfo.depositAmount = parseFloat($(obj).find(".depositAmount").val());
                        dealInfo.payService = parseFloat($(obj).find(".payService").html());
                        dealInfo.discountHide = parseFloat($(obj).find(".payService").html());
                        dealInfo.primaryAmount = parseFloat($(obj).find(".primary").val());
                        dealInfo.wholeDiscount = $("#totalDiscount").val();
                        var serviceActualPay = parseFloat($(obj).find(".realAmount").html());
                        if (newPayAmount >= serviceActualPay) {
                            dealInfo.serviceActualPay = parseFloat($(obj).find(".realAmount").html());
                            dealInfo.arrears = 0;
                            newPayAmount = newPayAmount - serviceActualPay;
                        } else {
                            dealInfo.serviceActualPay = newPayAmount;
                            dealInfo.arrears = serviceActualPay - newPayAmount;
                            newPayAmount = 0;
                        }
                        dealInfo.intamount = intamount;
                        dealInfo.lowestPriceBill = lowestPriceBill;
                        billList.push(dealInfo);
                    }
                } else {
                    for (var i = 0; i < dataList.length; i++) {
                        var obj = dataList[i];
                        var dealInfo = {};
                        dealInfo.reservationsIdx = reservationsIdx;
                        var treatmentUnit = $("#treatmentUnitHtml").html();
                        dealInfo.customerId = customerId;
                        dealInfo.reservationsId = reservationsId;
                        dealInfo.remarks = remarks;
                        dealInfo.payServiceId = $(obj).find(".payServiceId").val();
                        dealInfo.vipPayserviceId = $(obj).find(".vipPayserviceId").val();
                        dealInfo.payServiceNum = parseFloat($(obj).find(".num").html());
                        var payServiceNum = parseFloat($(obj).find(".num").html());
                        var doctor = $(obj).find(".doctor").val();
                        var nurse = $("#projectNurse").val();
                        if (payServiceNum < 1) {
                            layer.msg('请输入项目数量！', {time: 1000, icon: 2});
                            count = 0;
                            return false;
                        }
                        if ((doctor == null || doctor == "") && (nurse == null || nurse == "")) {
                            layer.msg('请选择医生或护士！', {time: 1000, icon: 2});
                            count = 0;
                            return false;
                        }
                        if ("洁牙" == treatmentUnit) {
                            dealInfo.dentalHygienist = $(obj).find(".doctor").val();
                        } else {
                            dealInfo.dentalHygienist = "";
                        }
                        dealInfo.foldingPay = parseFloat($(obj).find(".amount").html());
                        dealInfo.doctor = $(obj).find(".doctor").val();
                        dealInfo.nurse = $("#projectNurse").val();
                        dealInfo.leftUp = $(obj).find(".leftUp").val();
                        dealInfo.leftDown = $(obj).find(".leftDown").val();
                        dealInfo.rightUp = $(obj).find(".rightUp").val();
                        dealInfo.rightDown = $(obj).find(".rightDown").val();
                        dealInfo.serviceActualPay = parseFloat($(obj).find(".realAmount").html());
                        dealInfo.deductionType = parseFloat($(obj).find(".deductionType").val());
                        var deductionType = $(obj).find(".deductionType").find("option:selected").text();
                        if (deductionType.indexOf("返现") >= 0) {
                            jfAmount = jfAmount + parseFloat($(obj).find(".deductionAmount").val());
                        }
                        earnestAmount = earnestAmount + parseFloat($(obj).find(".depositAmount").val());
                        dealInfo.deductionTypeName = parseFloat($(obj).find(".deductionType").html());
                        dealInfo.deductionAmount = parseFloat($(obj).find(".deductionAmount").val());
                        dealInfo.orderDiscount = parseFloat($(obj).find(".orderDiscount").val());
                        dealInfo.depositAmount = parseFloat($(obj).find(".depositAmount").val());
                        dealInfo.payService = parseFloat($(obj).find(".payService").html());
                        dealInfo.discountHide = parseFloat($(obj).find(".payService").html());
                        dealInfo.primaryAmount = parseFloat($(obj).find(".primary").val());
                        dealInfo.wholeDiscount = $("#totalDiscount").val();
                        dealInfo.arrears = 0;
                        dealInfo.intamount = intamount;
                        dealInfo.lowestPriceBill = lowestPriceBill;
                        billList.push(dealInfo);
                    }
                }
                if (earnestAmount > moneyBalance) {
                    layer.alert("储值划扣金额不能超过储值余额！");
                    count = 0;
                    return false;
                }
                if (jfAmount > jfBalance) {
                    layer.alert("返现抵扣金额不能超过返现余额");
                    count = 0;
                    return false;
                }
            } else if ($('#integral').is(':checked') && !$('#earnest').is(':checked')) {
                var totalJF = 0;
                var jfbalance = parseFloat($("#jfbalance").html());
                var totalSum1 = parseFloat($("#totalSum1").val());
                var payable = parseFloat($("#newPayAmount").val());
                if (totalSum1 != payable) {
                    for (var i = 0; i < dataList.length; i++) {
                        var obj = dataList[i];
                        var dealInfo = {};
                        dealInfo.reservationsIdx = reservationsIdx;
                        var treatmentUnit = $("#treatmentUnitHtml").html();
                        dealInfo.customerId = customerId;
                        dealInfo.reservationsId = reservationsId;
                        dealInfo.payServiceId = $(obj).find(".payServiceId").val();
                        dealInfo.vipPayserviceId = $(obj).find(".vipPayserviceId").val();
                        dealInfo.payServiceNum = parseFloat($(obj).find(".num").html());
                        var payServiceNum = parseFloat($(obj).find(".num").html());
                        var doctor = $(obj).find(".doctor").val();
                        var nurse = $("#projectNurse").val();
                        if (payServiceNum < 1) {
                            layer.msg('请输入项目数量！', {time: 1000, icon: 2});
                            count = 0;
                            return false;
                        }
                        if ((doctor == null || doctor == "") && (nurse == null || nurse == "")) {
                            layer.msg('请选择医生或护士！', {time: 1000, icon: 2});
                            count = 0;
                            return false;
                        }
                        if ("洁牙" == treatmentUnit) {
                            dealInfo.dentalHygienist = $(obj).find(".doctor").val();
                        } else {
                            dealInfo.dentalHygienist = "";
                        }
                        dealInfo.foldingPay = parseFloat($(obj).find(".amount").html());
                        dealInfo.doctor = $(obj).find(".doctor").val();
                        dealInfo.nurse = $("#projectNurse").val();
                        dealInfo.remarks = remarks;
                        dealInfo.leftUp = $(obj).find(".leftUp").val();
                        dealInfo.leftDown = $(obj).find(".leftDown").val();
                        dealInfo.rightUp = $(obj).find(".rightUp").val();
                        dealInfo.rightDown = $(obj).find(".rightDown").val();
                        dealInfo.deductionType = parseFloat($(obj).find(".deductionType").val());
                        var deductionType = $(obj).find(".deductionType").find("option:selected").text();
                        dealInfo.deductionTypeName = parseFloat($(obj).find(".deductionType").html());
                        dealInfo.deductionAmount = parseFloat($(obj).find(".deductionAmount").val());
                        dealInfo.orderDiscount = parseFloat($(obj).find(".orderDiscount").val());
                        dealInfo.depositAmount = 0;
                        var deductionAmount = parseFloat($(obj).find(".deductionAmount").val());
                        if (deductionType.indexOf('返现') >= 0) {
                            totalJF += deductionAmount;
                        }
                        dealInfo.payService = parseFloat($(obj).find(".payService").html());
                        dealInfo.discountHide = parseFloat($(obj).find(".payService").html());
                        dealInfo.primaryAmount = parseFloat($(obj).find(".primary").val());
                        dealInfo.wholeDiscount = $("#totalDiscount").val();
                        var serviceActualPay = parseFloat($(obj).find(".realAmount").html());
                        if (payable >= serviceActualPay) {
                            dealInfo.serviceActualPay = parseFloat($(obj).find(".realAmount").html());
                            dealInfo.arrears = 0;
                            payable = payable - serviceActualPay;
                        } else {
                            dealInfo.serviceActualPay = payable;
                            dealInfo.arrears = serviceActualPay - payable;
                            payable = 0;
                        }
                        dealInfo.intamount = intamount;
                        dealInfo.lowestPriceBill = lowestPriceBill;
                        billList.push(dealInfo);
                    }
                } else {
                    for (var i = 0; i < dataList.length; i++) {
                        var obj = dataList[i];
                        var dealInfo = {};
                        dealInfo.reservationsIdx = reservationsIdx;
                        var treatmentUnit = $("#treatmentUnitHtml").html();
                        dealInfo.customerId = customerId;
                        dealInfo.reservationsId = reservationsId;
                        dealInfo.payServiceId = $(obj).find(".payServiceId").val();
                        dealInfo.vipPayserviceId = $(obj).find(".vipPayserviceId").val();
                        dealInfo.payServiceNum = parseFloat($(obj).find(".num").html());
                        var payServiceNum = parseFloat($(obj).find(".num").html());
                        var doctor = $(obj).find(".doctor").val();
                        var nurse = $("#projectNurse").val();
                        if (payServiceNum < 1) {
                            layer.msg('请输入项目数量！', {time: 1000, icon: 2});
                            count = 0;
                            return false
                        }
                        if ((doctor == null || doctor == "") && (nurse == null || nurse == "")) {
                            layer.msg('请选择医生或护士！', {time: 1000, icon: 2});
                            count = 0;
                            return false
                        }
                        if ("洁牙" == treatmentUnit) {
                            dealInfo.dentalHygienist = $(obj).find(".doctor").val()
                        } else {
                            dealInfo.dentalHygienist = ""
                        }
                        dealInfo.foldingPay = parseFloat($(obj).find(".amount").html());
                        dealInfo.doctor = $(obj).find(".doctor").val();
                        dealInfo.nurse = $("#projectNurse").val();
                        dealInfo.remarks = remarks;
                        dealInfo.leftUp = $(obj).find(".leftUp").val();
                        dealInfo.leftDown = $(obj).find(".leftDown").val();
                        dealInfo.rightUp = $(obj).find(".rightUp").val();
                        dealInfo.rightDown = $(obj).find(".rightDown").val();
                        dealInfo.serviceActualPay = parseFloat($(obj).find(".realAmount").html());
                        dealInfo.deductionType = parseFloat($(obj).find(".deductionType").val());
                        dealInfo.deductionTypeName = parseFloat($(obj).find(".deductionType").html());
                        dealInfo.deductionAmount = parseFloat($(obj).find(".deductionAmount").val());
                        dealInfo.orderDiscount = parseFloat($(obj).find(".orderDiscount").val());
                        dealInfo.depositAmount = 0;
                        var deductionAmount = parseFloat($(obj).find(".deductionAmount").val());
                        var deductionType = $(obj).find(".deductionType").find("option:selected").text();
                        if (deductionType.indexOf('返现') >= 0) {
                            totalJF += deductionAmount
                        }
                        dealInfo.payService = parseFloat($(obj).find(".payService").html());
                        dealInfo.discountHide = parseFloat($(obj).find(".payService").html());
                        dealInfo.primaryAmount = parseFloat($(obj).find(".primary").val());
                        dealInfo.wholeDiscount = $("#totalDiscount").val();
                        dealInfo.arrears = 0;
                        dealInfo.intamount = intamount;
                        dealInfo.lowestPriceBill = lowestPriceBill;
                        billList.push(dealInfo);
                    }
                }
                if (totalJF > jfbalance) {
                    layer.alert("返现抵扣金额不能超过返现余额！");
                    count = 0;
                    return false
                }
            } else if (!$('#integral').is(':checked') && $('#earnest').is(':checked')) {
                var moneyBalance = parseFloat($("#moneyBalance").html());
                var payable = parseFloat($("#newPayAmount").val());
                var realTotalSum2 = parseFloat($("#realTotalSum2").val());
                var totalDepositAmount = 0;
                if (realTotalSum2 != payable) {
                    for (var i = 0; i < dataList.length; i++) {
                        var obj = dataList[i];
                        var dealInfo = {};
                        dealInfo.reservationsIdx = reservationsIdx;
                        var treatmentUnit = $("#treatmentUnitHtml").html();
                        dealInfo.customerId = customerId;
                        dealInfo.reservationsId = reservationsId;
                        dealInfo.payServiceId = $(obj).find(".payServiceId").val();
                        dealInfo.vipPayserviceId = $(obj).find(".vipPayserviceId").val();
                        dealInfo.payServiceNum = parseFloat($(obj).find(".num").html());
                        dealInfo.orderDiscount = parseFloat($(obj).find(".orderDiscount").val());
                        var payServiceNum = parseFloat($(obj).find(".num").html());
                        var doctor = $(obj).find(".doctor").val();
                        var nurse = $("#projectNurse").val();
                        if (payServiceNum < 1) {
                            layer.msg('请输入项目数量！', {time: 1000, icon: 2});
                            count = 0;
                            return false
                        }
                        if ((doctor == null || doctor == "") && (nurse == null || nurse == "")) {
                            layer.msg('请选择医生或护士！', {time: 1000, icon: 2});
                            count = 0;
                            return false
                        }
                        if ("洁牙" == treatmentUnit) {
                            dealInfo.dentalHygienist = $(obj).find(".doctor").val()
                        } else {
                            dealInfo.dentalHygienist = ""
                        }
                        dealInfo.foldingPay = parseFloat($(obj).find(".amount").html());
                        dealInfo.doctor = $(obj).find(".doctor").val();
                        dealInfo.nurse = $("#projectNurse").val();
                        dealInfo.remarks = remarks;
                        dealInfo.leftUp = $(obj).find(".leftUp").val();
                        dealInfo.leftDown = $(obj).find(".leftDown").val();
                        dealInfo.rightUp = $(obj).find(".rightUp").val();
                        dealInfo.rightDown = $(obj).find(".rightDown").val();
                        var depositAmount = parseFloat($(obj).find(".depositAmount").val());
                        var serviceActualPay = parseFloat($(obj).find(".realAmount").html());
                        dealInfo.depositAmount = parseFloat($(obj).find(".depositAmount").val());
                        if (payable >= serviceActualPay + depositAmount) {
                            dealInfo.serviceActualPay = parseFloat($(obj).find(".realAmount").html());
                            dealInfo.arrears = 0;
                            payable = payable - serviceActualPay
                        } else {
                            dealInfo.serviceActualPay = payable;
                            dealInfo.arrears = serviceActualPay - payable;
                            payable = 0
                        }
                        dealInfo.deductionType = "0";
                        dealInfo.deductionTypeName = "";
                        dealInfo.deductionAmount = 0;
                        dealInfo.payService = parseFloat($(obj).find(".payService").html());
                        dealInfo.discountHide = parseFloat($(obj).find(".payService").html());
                        dealInfo.primaryAmount = parseFloat($(obj).find(".primary").val());
                        dealInfo.wholeDiscount = $("#totalDiscount").val();
                        totalDepositAmount = totalDepositAmount + depositAmount;
                        dealInfo.intamount = intamount;
                        dealInfo.lowestPriceBill = lowestPriceBill;
                        billList.push(dealInfo);
                    }
                } else {
                    for (var i = 0; i < dataList.length; i++) {
                        var obj = dataList[i];
                        var dealInfo = {};
                        dealInfo.reservationsIdx = reservationsIdx;
                        var treatmentUnit = $("#treatmentUnitHtml").html();
                        dealInfo.customerId = customerId;
                        dealInfo.reservationsId = reservationsId;
                        dealInfo.payServiceId = $(obj).find(".payServiceId").val();
                        dealInfo.vipPayserviceId = $(obj).find(".vipPayserviceId").val();
                        dealInfo.payServiceNum = parseFloat($(obj).find(".num").html());
                        dealInfo.orderDiscount = parseFloat($(obj).find(".orderDiscount").val());
                        var payServiceNum = parseFloat($(obj).find(".num").html());
                        var doctor = $(obj).find(".doctor").val();
                        var nurse = $("#projectNurse").val();
                        if (payServiceNum < 1) {
                            layer.msg('请输入项目数量！', {time: 1000, icon: 2});
                            count = 0;
                            return false;
                        }
                        if ((doctor == null || doctor == "") && (nurse == null || nurse == "")) {
                            layer.msg('请选择医生或护士！', {time: 1000, icon: 2});
                            count = 0;
                            return false;
                        }
                        if ("洁牙" == treatmentUnit) {
                            dealInfo.dentalHygienist = $(obj).find(".doctor").val()
                        } else {
                            dealInfo.dentalHygienist = ""
                        }
                        dealInfo.foldingPay = parseFloat($(obj).find(".amount").html());
                        dealInfo.doctor = $(obj).find(".doctor").val();
                        dealInfo.nurse = $("#projectNurse").val();
                        dealInfo.remarks = remarks;
                        dealInfo.leftUp = $(obj).find(".leftUp").val();
                        dealInfo.leftDown = $(obj).find(".leftDown").val();
                        dealInfo.rightUp = $(obj).find(".rightUp").val();
                        dealInfo.rightDown = $(obj).find(".rightDown").val();
                        dealInfo.serviceActualPay = parseFloat($(obj).find(".realAmount").html());
                        dealInfo.deductionType = "0";
                        dealInfo.deductionTypeName = "";
                        dealInfo.deductionAmount = 0;
                        dealInfo.payService = parseFloat($(obj).find(".payService").html());
                        dealInfo.discountHide = parseFloat($(obj).find(".payService").html());
                        dealInfo.primaryAmount = parseFloat($(obj).find(".primary").val());
                        dealInfo.wholeDiscount = $("#totalDiscount").val();
                        var depositAmount = parseFloat($(obj).find(".depositAmount").val());
                        dealInfo.depositAmount = parseFloat($(obj).find(".depositAmount").val());
                        totalDepositAmount = totalDepositAmount + depositAmount;
                        dealInfo.arrears = 0;
                        dealInfo.intamount = intamount;
                        dealInfo.lowestPriceBill = lowestPriceBill;
                        billList.push(dealInfo);
                    }
                }
                if (totalDepositAmount > moneyBalance) {
                    layer.alert("储值划扣金额不能超过储值余额！");
                    count = 0;
                    return false;
                }
            }
            if (parseFloat($("#totalDiscount").val()) < 90) {
                var r = confirm("是否确定开单？");
                if (r == true) {
                    $.ajax({
                        url: Feng.ctxPath + "/consultant/getCustomerStatus/" + $("#customerId").val() ,
                        dataType: "json",
                        contentType: "application/json",
                        type: "POST",
                        success: function (data) {
                            if (data.split(",")[0] == '复诊') {
                                alert("复诊不能重新开单,请去进行重咨操作！");
                                count = 0;
                                return;
                            } else if (data.split(",")[1] > 0) {
                                alert("此患者还有未结账的单，不能再次开单！");
                                refundcount = 0;
                                return;
                            } else if (data.split(",")[2] == 3) {
                                alert("患者TC不是当前登录人，请联系前台分配患者！");
                                count = 0;
                                return;
                            } else {
                                count++;
                                if (count == 1) {
                                    $.ajax({
                                        url: Feng.ctxPath + "/consultant/openBillNew",
                                        dataType: "json",
                                        contentType: "application/json",
                                        data: JSON.stringify(billList),
                                        type: "POST",
                                        success: function (data) {
                                            if (data.split(",")[0] == 55) {
                                                alert("前台只能开洁牙项目！")
                                            } else if (data.split(",")[0] == 22) {
                                                alert("此患者已不在可开单状态");
                                                if (currentSeat == 'TC &gt; TC回访') {
                                                    window.parent.TcRevisit.table.refresh();
                                                } else if (currentSeat == 'TC &gt; TC看诊') {
                                                    window.parent.Consultant.table.refresh();
                                                } else if (currentSeat == 'TC &gt; 回访记录') {
                                                    window.parent.ConsultantRecord.table.refresh();
                                                } else if (currentSeat == 'TC &gt; 今日回访') {
                                                    window.parent.ConsultantReserve.table.refresh();
                                                } else if (currentSeat == 'TC &gt; 回访详情') {
                                                    window.parent.ReturnVisit.table.refresh();
                                                }
                                                parent.layer.close(windowNameIndex);
                                            } else {
                                                var operationTime = data.split(",")[1];
                                                var index = layer.open({
                                                    type: 2,
                                                    title: '开单打印',
                                                    area: ['60%', '100%'],
                                                    fix: true,
                                                    maxmin: true,
                                                    content: Feng.ctxPath + '/consultant/singlePrint/' + customerId + "/" + operationTime,
                                                    success: function () {
                                                        if($("#detail").val()=='isArrive') {
                                                            location.href = Feng.ctxPath + '/consultantDetails/consultantToDetailByTab/' + customerId + '/2/0';
                                                        }else{
                                                            location.href = Feng.ctxPath + '/consultantDetails/consultantToDetailByTab/' + customerId + '/3/0';
                                                        }
                                                        window.parent.Consultant.table.refresh()
                                                    }
                                                });
                                                this.layerIndex = index;
                                            }
                                        }
                                    })
                                }
                            }
                        }
                    })
                } else {
                }
            } else {
                $.ajax({
                    url: Feng.ctxPath + "/consultant/getCustomerStatus/" + $("#customerId").val() ,
                    dataType: "json",
                    contentType: "application/json",
                    type: "POST",
                    success: function (data) {
                        if (data.split(",")[0] == '复诊') {
                            alert("复诊不能重新开单,请去进行重咨操作！");
                            count = 0;
                            return
                        } else if (data.split(",")[1] > 0) {
                            alert("此患者还有未结账的单，不能再次开单！");
                            refundcount = 0;
                            return;
                        } else if (data.split(",")[2] == 3) {
                            alert("患者TC不是当前登录人，请联系前台分配患者！");
                            count = 0;
                            return
                        } else {
                            var r = confirm("是否确定开单？");
                            if (r == true) {
                                count++;
                                if (count == 1) {
                                    $.ajax({
                                        url: Feng.ctxPath + "/consultant/openBillNew",
                                        dataType: "json",
                                        contentType: "application/json",
                                        data: JSON.stringify(billList),
                                        type: "POST",
                                        success: function (data) {
                                            if (data.split(",")[0] == 55) {
                                                alert("前台只能开洁牙项目！")
                                            } else if (data.split(",")[0] == 22) {
                                                alert("此患者已不在可开单状态");
                                                if (currentSeat == 'TC &gt; TC回访') {
                                                    window.parent.TcRevisit.table.refresh();
                                                } else if (currentSeat == 'TC &gt; TC看诊') {
                                                    window.parent.Consultant.table.refresh();
                                                } else if (currentSeat == 'TC &gt; 回访记录') {
                                                    window.parent.ConsultantRecord.table.refresh();
                                                } else if (currentSeat == 'TC &gt; 今日回访') {
                                                    window.parent.ConsultantReserve.table.refresh();
                                                } else if (currentSeat == 'TC &gt; 回访详情') {
                                                    window.parent.ReturnVisit.table.refresh();
                                                }
                                                parent.layer.close(windowNameIndex)
                                            } else {
                                                var operationTime = data.split(",")[1];
                                                var index = layer.open({
                                                    type: 2,
                                                    title: '开单打印',
                                                    area: ['60%', '100%'],
                                                    fix: true,
                                                    maxmin: true,
                                                    content: Feng.ctxPath + '/consultant/singlePrint/' + customerId + "/" + operationTime,
                                                    success: function () {
                                                        if($("#detail").val()=='isArrive') {
                                                            location.href = Feng.ctxPath + '/consultantDetails/consultantToDetailByTab/' + customerId + '/2/0';
                                                        }else{
                                                            location.href = Feng.ctxPath + '/consultantDetails/consultantToDetailByTab/' + customerId + '/3/0';
                                                        }
                                                        window.parent.Consultant.table.refresh();
                                                    }
                                                })
                                            }
                                        }
                                    })
                                }
                            } else {
                            }
                        }
                    }
                })
            }
        } else {
            var dataList = $(".proDealInfo");
            var billList = [];
            var newTotalSum = parseFloat($("#newTotalSum").val());
            var payable = parseFloat($("#newPayAmount").val());
            if (newTotalSum == payable) {
                for (var i = 0; i < dataList.length; i++) {
                    var obj = dataList[i];
                    var dealInfo = {};
                    dealInfo.reservationsIdx = reservationsIdx;
                    var treatmentUnit = $("#treatmentUnit").val();
                    dealInfo.customerId = customerId;
                    dealInfo.reservationsId = reservationsId;
                    dealInfo.payServiceId = $(obj).find(".payServiceId").val();
                    dealInfo.vipPayserviceId = $(obj).find(".vipPayserviceId").val();
                    dealInfo.payServiceNum = parseFloat($(obj).find(".num").val());
                    dealInfo.deductionType = 0;
                    dealInfo.deductionAmount = 0;
                    dealInfo.depositAmount = 0;
                    var payServiceNum = parseFloat($(obj).find(".num").val());
                    var doctor = $(obj).find(".doctor").val();
                    var nurse = $("#projectNurse").val();
                    if (payServiceNum < 1) {
                        layer.msg('请输入项目数量！', {time: 1000, icon: 2});
                        count = 0;
                        return false
                    }
                    if ((doctor == null || doctor == "") && (nurse == null || nurse == "")) {
                        layer.msg('请选择医生或护士！', {time: 1000, icon: 2});
                        count = 0;
                        return false
                    }
                    if ("洁牙" == treatmentUnit) {
                        dealInfo.dentalHygienist = $(obj).find(".doctor").val()
                    } else {
                        dealInfo.dentalHygienist = ""
                    }
                    dealInfo.foldingPay = parseFloat($(obj).find(".amount").val());
                    dealInfo.doctor = $(obj).find(".doctor").val();
                    dealInfo.nurse = $("#projectNurse").val();
                    dealInfo.remarks = remarks;
                    dealInfo.orderDiscount = $(obj).find(".discount").val();
                    dealInfo.leftUp = $(obj).find(".leftUp").html();
                    dealInfo.leftDown = $(obj).find(".leftDown").html();
                    dealInfo.rightUp = $(obj).find(".rightUp").html();
                    dealInfo.rightDown = $(obj).find(".rightDown").html();
                    dealInfo.serviceActualPay = parseFloat($(obj).find(".realAmount").val());
                    dealInfo.deductionType = "";
                    dealInfo.deductionTypeName = "";
                    dealInfo.deductionAmount = 0;
                    dealInfo.depositAmount = 0;
                    dealInfo.payService = parseFloat($(obj).find(".payService").val());
                    dealInfo.discountHide = parseFloat($(obj).find(".payService").val());
                    dealInfo.primaryAmount = parseFloat($(obj).find(".primary").val());
                    dealInfo.wholeDiscount = $("#totalDiscount").val();
                    dealInfo.arrears = 0;
                    dealInfo.intamount = intamount;
                    dealInfo.lowestPriceBill = lowestPriceBill;
                    billList.push(dealInfo);
                }
            } else {
                for (var i = 0; i < dataList.length; i++) {
                    var obj = dataList[i];
                    var dealInfo = {};
                    dealInfo.reservationsIdx = reservationsIdx;
                    var treatmentUnit = $("#treatmentUnitHtml").html();
                    dealInfo.customerId = customerId;
                    dealInfo.reservationsId = reservationsId;
                    dealInfo.payServiceId = $(obj).find(".payServiceId").val();
                    dealInfo.vipPayserviceId = $(obj).find(".vipPayserviceId").val();
                    dealInfo.payServiceNum = parseFloat($(obj).find(".num").val());
                    dealInfo.deductionType = 0;
                    dealInfo.deductionAmount = 0;
                    dealInfo.remarks = remarks;
                    dealInfo.depositAmount = 0;
                    var payServiceNum = parseFloat($(obj).find(".num").val());
                    var doctor = $(obj).find(".doctor").val();
                    var nurse = $("#projectNurse").val();
                    if (payServiceNum < 1) {
                        layer.msg('请输入项目数量！', {time: 1000, icon: 2});
                        count = 0;
                        return false
                    }
                    if ((doctor == null || doctor == "") && (nurse == null || nurse == "")) {
                        layer.msg('请选择医生或护士！', {time: 1000, icon: 2});
                        count = 0;
                        return false
                    }
                    if ("洁牙" == treatmentUnit) {
                        dealInfo.dentalHygienist = $(obj).find(".doctor").val()
                    } else {
                        dealInfo.dentalHygienist = ""
                    }
                    dealInfo.foldingPay = parseFloat($(obj).find(".amount").val());
                    dealInfo.doctor = $(obj).find(".doctor").val();
                    dealInfo.nurse = $("#projectNurse").val();
                    dealInfo.orderDiscount = $(obj).find(".discount").val();
                    dealInfo.leftUp = $(obj).find(".leftUp").html();
                    dealInfo.leftDown = $(obj).find(".leftDown").html();
                    dealInfo.rightUp = $(obj).find(".rightUp").html();
                    dealInfo.rightDown = $(obj).find(".rightDown").html();
                    var serviceActualPay = parseFloat($(obj).find(".realAmount").val());
                    if (payable >= serviceActualPay) {
                        dealInfo.serviceActualPay = parseFloat($(obj).find(".realAmount").val());
                        dealInfo.arrears = 0;
                        payable = payable - serviceActualPay
                    } else {
                        dealInfo.serviceActualPay = payable;
                        dealInfo.arrears = serviceActualPay - payable;
                        payable = 0
                    }
                    dealInfo.deductionType = "";
                    dealInfo.deductionTypeName = "";
                    dealInfo.deductionAmount = 0;
                    dealInfo.depositAmount = 0;
                    dealInfo.payService = parseFloat($(obj).find(".payService").val());
                    dealInfo.discountHide = parseFloat($(obj).find(".discountHide").val());
                    dealInfo.primaryAmount = parseFloat($(obj).find(".primary").val());
                    dealInfo.wholeDiscount = $("#totalDiscount").val();
                    dealInfo.intamount = intamount;
                    dealInfo.lowestPriceBill = lowestPriceBill;
                    billList.push(dealInfo);
                }
            }
            if (parseFloat($("#totalDiscount").val()) < 90) {
                var r = confirm("是否确定开单？");
                if (r == true) {
                    $.ajax({
                        url: Feng.ctxPath + "/consultant/getCustomerStatus/" + $("#customerId").val() ,
                        dataType: "json",
                        contentType: "application/json",
                        type: "POST",
                        success: function (data) {
                            if (data.split(",")[0] == '复诊') {
                                alert("复诊不能重新开单,请去进行重咨操作！");
                                count = 0;
                                return
                            } else if (data.split(",")[1] > 0) {
                                alert("此患者还有未结账的单，不能再次开单！");
                                refundcount = 0;
                                return;
                            } else if (data.split(",")[2] == 3) {
                                alert("患者TC不是当前登录人，请联系前台分配患者！");
                                count = 0;
                                return
                            } else {
                                count++
                                if (count == 1) {
                                    $.ajax({
                                        url: Feng.ctxPath + "/consultant/openBillNew",
                                        dataType: "json",
                                        contentType: "application/json",
                                        data: JSON.stringify(billList),
                                        type: "POST",
                                        success: function (data) {
                                            if (data.split(",")[0] == 55) {
                                                alert("前台只能开洁牙项目！")
                                            } else if (data.split(",")[0] == 22) {
                                                alert("此患者已不在可开单状态");
                                                if (currentSeat == 'TC &gt; TC回访') {
                                                    window.parent.TcRevisit.table.refresh();
                                                } else if (currentSeat == 'TC &gt; TC看诊') {
                                                    window.parent.Consultant.table.refresh();
                                                } else if (currentSeat == 'TC &gt; 回访记录') {
                                                    window.parent.ConsultantRecord.table.refresh();
                                                } else if (currentSeat == 'TC &gt; 今日回访') {
                                                    window.parent.ConsultantReserve.table.refresh();
                                                } else if (currentSeat == 'TC &gt; 回访详情') {
                                                    window.parent.ReturnVisit.table.refresh();
                                                }
                                                parent.layer.close(windowNameIndex);
                                            } else {
                                                var operationTime = data.split(",")[1];
                                                var index = layer.open({
                                                    type: 2,
                                                    title: '开单打印',
                                                    area: ['60%', '100%'],
                                                    fix: true,
                                                    maxmin: true,
                                                    content: Feng.ctxPath + '/consultant/singlePrint/' + customerId + "/" + operationTime,
                                                    success: function () {
                                                        if($("#detail").val()=='isArrive') {
                                                            location.href = Feng.ctxPath + '/consultantDetails/consultantToDetailByTab/' + customerId + '/2/0';
                                                        }else{
                                                            location.href = Feng.ctxPath + '/consultantDetails/consultantToDetailByTab/' + customerId + '/3/0';
                                                        }
                                                        window.parent.Consultant.table.refresh();
                                                    }
                                                })
                                            }
                                        }
                                    })
                                }
                            }
                        }
                    })
                } else {
                }
            } else {
                $.ajax({
                        url: Feng.ctxPath + "/consultant/getCustomerStatus/" + $("#customerId").val() ,
                        dataType: "json",
                        contentType: "application/json",
                        type: "POST",
                        success: function (data) {
                            if (data.split(",")[0] == '复诊') {
                                alert("复诊不能重新开单,请去进行重咨操作！");
                                count = 0;
                                return
                            } else if (data.split(",")[1] > 0) {
                                alert("此患者还有未结账的单，不能再次开单！");
                                refundcount = 0;
                                return;
                            } else if (data.split(",")[2] == 3) {
                                alert("患者TC不是当前登录人，请联系前台分配患者！");
                                count = 0;
                                return
                            } else {
                                var r = confirm("是否确定开单？");
                                if (r == true) {
                                    count++;
                                    if (count == 1) {
                                        $.ajax({
                                            url: Feng.ctxPath + "/consultant/openBillNew",
                                            dataType: "json",
                                            contentType: "application/json",
                                            data: JSON.stringify(billList),
                                            type: "POST",
                                            success: function (data) {
                                                if (data.split(",")[0] == 55) {
                                                    alert("前台只能开洁牙项目！")
                                                } else if (data.split(",")[0] == 22) {
                                                    alert("此患者已不在可开单状态");
                                                    if (currentSeat == 'TC &gt; TC回访') {
                                                        window.parent.TcRevisit.table.refresh();
                                                    } else if (currentSeat == 'TC &gt; TC看诊') {
                                                        window.parent.Consultant.table.refresh();
                                                    } else if (currentSeat == 'TC &gt; 回访记录') {
                                                        window.parent.ConsultantRecord.table.refresh();
                                                    } else if (currentSeat == 'TC &gt; 今日回访') {
                                                        window.parent.ConsultantReserve.table.refresh();
                                                    } else if (currentSeat == 'TC &gt; 回访详情') {
                                                        window.parent.ReturnVisit.table.refresh();
                                                    }
                                                    parent.layer.close(windowNameIndex);
                                                } else {
                                                    var operationTime = data.split(",")[1];
                                                    var index = layer.open({
                                                        type: 2,
                                                        title: '开单打印',
                                                        area: ['60%', '100%'],
                                                        fix: true,
                                                        maxmin: true,
                                                        content: Feng.ctxPath + '/consultant/singlePrint/' + customerId + "/" + operationTime,
                                                        success: function () {
                                                            if($("#detail").val()=='isArrive') {
                                                                location.href = Feng.ctxPath + '/consultantDetails/consultantToDetailByTab/' + customerId + '/2/0';
                                                            }else{
                                                                location.href = Feng.ctxPath + '/consultantDetails/consultantToDetailByTab/' + customerId + '/3/0';
                                                            }
                                                            window.parent.Consultant.table.refresh();
                                                        }
                                                    })
                                                }
                                            }
                                        })
                                    }
                                }
                            }
                        }
                    }
                )
            }
        }
    } else {
        alert("不允许操作昨天的数据,需要前台重咨,要计算门诊人数！");
        count = 0;
        return false;
    }
};

//刪除此單
deleteOrder = function (customerId, reservationsId, operationTime, getTime) {
    layer.confirm('是否确认删除该开单记录？', {btn: ['确定', '取消'], shade: false}, function (index, layero) {
        var ajax = new $ax(Feng.ctxPath + "/consultant/deleteOrder", function (data) {
            if (data == 111) {
                layer.close(index);
                Feng.success("此单前台已结账，删除失败!");
                if($("#detail").val()=='isArrive') {
                    location.href = Feng.ctxPath + '/consultantDetails/consultantToDetailByTab/' + customerId + '/2/0';
                }else{
                    location.href = Feng.ctxPath + '/consultantDetails/consultantToDetailByTab/' + customerId + '/3/0';
                }
            } else if (data > 0) {
                layer.close(index);
                Feng.success("删除成功!");
                if($("#detail").val()=='isArrive') {
                    location.href = Feng.ctxPath + '/consultantDetails/consultantToDetailByTab/' + customerId + '/2/0';
                }else{
                    location.href = Feng.ctxPath + '/consultantDetails/consultantToDetailByTab/' + customerId + '/3/0';
                }
            } else {
                layer.close(index);
                Feng.success("删除失败!");
                if($("#detail").val()=='isArrive') {
                    location.href = Feng.ctxPath + '/consultantDetails/consultantToDetailByTab/' + customerId + '/2/0';
                }else{
                    location.href = Feng.ctxPath + '/consultantDetails/consultantToDetailByTab/' + customerId + '/3/0';
                }
            }
        }, function (data) {
            Feng.error("删除失败!")
        });
        ajax.set("customerId", customerId);
        ajax.set("reservationsId", reservationsId);
        ajax.set("operationTime", operationTime);
        ajax.set("getTime", getTime);
        ajax.start();
    })
};
//重開此單
reDeal = function (customerId, reservationsId, operationTime, getTime, department) {
    layer.confirm('是否确认重开此单？', {btn: ['确定', '取消'], shade: false}, function (index, layero) {
        var ajax = new $ax(Feng.ctxPath + "/consultant/reDeal", function (data) {
            if (data == 111) {
                layer.close(index);
                Feng.success("此单前台已结账，重开此单失败!");
                if($("#detail").val()=='isArrive') {
                    location.href = Feng.ctxPath + '/consultantDetails/consultantToDetailByTab/' + customerId + '/2/0';
                }else{
                    location.href = Feng.ctxPath + '/consultantDetails/consultantToDetailByTab/' + customerId + '/3/0';
                }
            } else if (data == 222) {
                layer.close(index);
                Feng.success("请前台对该患者此单所在科室进行重咨后再重开此单！");
            } else if (data > 0) {
                layer.close(index);
                Feng.success("重开此单成功!请联系前台结账！");
                if($("#detail").val()=='isArrive') {
                    location.href = Feng.ctxPath + '/consultantDetails/consultantToDetailByTab/' + customerId + '/2/0';
                }else{
                    location.href = Feng.ctxPath + '/consultantDetails/consultantToDetailByTab/' + customerId + '/3/0';
                }
            } else {
                layer.close(index);
                Feng.success("重开此单权限被限制!请联系系统管理员！");
                if($("#detail").val()=='isArrive') {
                    location.href = Feng.ctxPath + '/consultantDetails/consultantToDetailByTab/' + customerId + '/2/0';
                }else{
                    location.href = Feng.ctxPath + '/consultantDetails/consultantToDetailByTab/' + customerId + '/3/0';
                }
            }
        }, function (data) {
            alert("没有权限，请联系系统管理员！");
            parent.layer.close(windowNameIndex);
        });
        ajax.set("reservationsId", reservationsId);
        ajax.set("customerId", customerId);
        ajax.set("operationTime", operationTime);
        ajax.set("getTime", getTime);
        ajax.set("department", department);
        ajax.start();
    })
};

singlePrint = function (customerId, reservationsId, getTime, operationTime, outpatientName) {
    var ids = customerId + "," + reservationsId + "," + getTime + "," + operationTime + "," + outpatientName;
    var index = layer.open({
        type: 2,
        title: '开单打印',
        area: ['60%', '100%'],
        fix: true,
        maxmin: true,
        content: Feng.ctxPath + '/consultant/singlePrintt/' + ids,
        success: function () {
        }
    });
    this.layerIndex = index;
};

IsDealInfoDlg.initData = function () {
    var seletecustomerSex = $('#customerSexValue').val();
    if ($('#id').val() != "") {
        $("#customerSex option[value='" + seletecustomerSex + "']").attr("selected", "selected");
    }
    if ($('#id').val() != "") {
        $("#select1 option[value='" + seletecustomerSex + "']").attr("selected", "selected");
    }
};


//  判断今天是否到店
function checkIsYesterdayCust() {
    let arrivalTime = $("#arrivalTimeStr").val(); // 最近一次到店时间
    let newTime = moment(new Date()).format('YYYY-MM-DD'); // 今天
    return moment(newTime).isBefore(arrivalTime);   //  比较两个时间大小
}
//  开单函数封装
IsDealInfoDlg.tcBilling = function (type) {
    if(type === 'distribution'){
        layer.close(layer.index);
    }

    let currentSeat = parent.parent.$('#currentSeat').html();  //选定界面
    if(checkIsYesterdayCust()){
        let customerId = $('#customerId').val();               // 到店ID
        let reservationsId = $("#reservationsId").val();       // 预约ID
        let reservationsIdx = $('#reservationsIdx').val();     // 使用其他会员ID
        let nurse = $("#projectNurse").val();                  // 护士
        let totalDiscount = $("#totalDiscount").val();         // 整单折扣
        let lowestPriceBill = $('#lowestPriceBill').val();     // 最低价格
        let newArrears = parseFloat($("#newArrears").val());   // 欠费金额
        let proRemark = $("#proRemark").val();
        let remarks = proRemark.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(/\s/g, ' ');  // 备注

        let billList = []; // 参数集合

        //  判断是否使用储值 or 返现
        if($('#integral').is(':checked') || $('#earnest').is(':checked')){
            let deductionDealList = $(".deductionDealList");   // 项目集合
            for(let i = 0 ; i < deductionDealList.length ; i ++){
                let obj = deductionDealList[i];
                let treatmentUnit = $("#treatmentUnit").val(); // 科室
                let doctor = $(obj).find(".doctor").val();     // 医生
                let dealInfo = {
                    customerId: customerId,           // 到店ID
                    reservationsId: reservationsId,   // 预约ID
                    reservationsIdx: reservationsIdx, // 使用其他会员ID
                    payServiceId: $(obj).find(".payServiceId").val(),       // 项目ID
                    vipPayserviceId: $(obj).find(".vipPayserviceId").val(), // 会员项目
                    leftDown: $(obj).find(".leftDown").val(),    // 左下牙位
                    leftUp: $(obj).find(".leftUp").val(),        // 左上牙位
                    rightUp: $(obj).find(".rightUp").val(),      // 右上牙位
                    rightDown: $(obj).find(".rightDown").val(),  // 右下牙位
                    payService:parseFloat($(obj).find(".payService").html()),       // 单价
                    discountHide: parseFloat($(obj).find(".payService").html()),    // 打折前单价
                    foldingPay: parseFloat($(obj).find(".amount").html()),          // 折后金额
                    payServiceNum: parseFloat($(obj).find(".num").html()),          // 数量
                    orderDiscount: parseFloat($(obj).find(".orderDiscount").val()), // 折扣
                    primaryAmount: parseFloat($(obj).find(".primary").val()),       // 打折前总价
                    doctor: $(obj).find(".doctor").val(), // 医生
                    nurse: nurse,      // 护士
                    remarks: remarks,  // 备注
                    intamount: 0,
                    wholeDiscount: totalDiscount,   // 整单折扣
                    lowestPriceBill: lowestPriceBill,  // 最低价格
                    dentalHygienist: treatmentUnit === "洁牙" ? $(obj).find(".doctor").val() : ""
                };
                // 返现储值同时使用
                if($('#integral').is(':checked') && $('#earnest').is(':checked')){
                    dealInfo.deductionType = parseFloat($(obj).find(".deductionType").val());       // 抵扣方式
                    dealInfo.deductionAmount = parseFloat($(obj).find(".deductionAmount").val());   // 抵用金额
                    dealInfo.depositAmount = parseFloat($(obj).find(".depositAmount").val());       // 划扣储值
                    dealInfo.deductionTypeName = $(obj).find(".deductionType").find("option:selected").text();  // 抵扣名称
                }
                // 只使用返现
                else if($('#integral').is(':checked') && !$('#earnest').is(':checked')){
                    dealInfo.deductionType = parseFloat($(obj).find(".deductionType").val());       // 抵扣方式
                    dealInfo.deductionAmount = parseFloat($(obj).find(".deductionAmount").val());   // 抵用金额
                    dealInfo.depositAmount = 0;                                                     // 划扣储值
                    dealInfo.deductionTypeName = $(obj).find(".deductionType").find("option:selected").text();  // 抵扣名称
                }
                // 只使用储值
                else if(!$('#integral').is(':checked') && $('#earnest').is(':checked')){
                    dealInfo.deductionType = "0";                                               // 抵扣方式
                    dealInfo.deductionAmount = 0;                                               // 抵用金额
                    dealInfo.depositAmount = parseFloat($(obj).find(".depositAmount").val());   // 划扣储值
                    dealInfo.deductionTypeName = "";                                            // 抵扣名称
                }
                // 判断是否欠费
                if(newArrears > 0){
                    dealInfo.arrears = parseFloat($(obj).find(".realAmount").html()) - parseFloat($("#distributionTips .distributionInput").eq(i).val());        // 欠费
                    dealInfo.serviceActualPay = parseFloat($("#distributionTips .distributionInput").eq(i).val());   // 项目实付金额
                }else {
                    dealInfo.arrears = 0;        // 欠费
                    dealInfo.serviceActualPay = parseFloat($(obj).find(".realAmount").html());   // 项目实付金额
                }
                if(parseFloat($(obj).find(".num").val()) < 1){
                    layer.msg('请输入项目数量！', {time: 1000, icon: 2});
                    return false
                }
                if ((doctor === null || doctor === "") && (nurse === null || nurse === "")) {
                    layer.msg('请选择医生或护士！', {time: 1000, icon: 2});
                    return false
                }
                billList.push(dealInfo);
            }
        }
        else {
            let proDealInfo = $(".proDealInfo");   // 项目集合
            for(let i = 0 ; i < proDealInfo.length ; i ++){
                let obj = proDealInfo[i];
                let treatmentUnit = $("#treatmentUnit").val(); // 科室
                let doctor = $(obj).find(".doctor").val();     // 医生
                let dealInfo = {
                    customerId: customerId,           // 到店ID
                    reservationsId: reservationsId,   // 预约ID
                    reservationsIdx: reservationsIdx, // 使用其他会员ID
                    payServiceId: $(obj).find(".payServiceId").val(),       // 项目ID
                    vipPayserviceId: $(obj).find(".vipPayserviceId").val(), // 会员项目
                    leftDown: $(obj).find(".leftDown").html(),    // 左下牙位
                    leftUp: $(obj).find(".leftUp").html(),        // 左上牙位
                    rightUp: $(obj).find(".rightUp").html(),      // 右上牙位
                    rightDown: $(obj).find(".rightDown").html(),  // 右下牙位
                    payService:parseFloat($(obj).find(".payService").val()),    // 单价
                    discountHide: parseFloat($(obj).find(".payService").val()), // 打折前单价
                    foldingPay: parseFloat($(obj).find(".amount").val()),       // 折后金额
                    payServiceNum: parseFloat($(obj).find(".num").val()),       // 数量
                    orderDiscount: $(obj).find(".discount").val(),              // 折扣
                    primaryAmount: parseFloat($(obj).find(".primary").val()),   // 打折前总价
                    doctor: $(obj).find(".doctor").val(), // 医生
                    nurse: nurse,      // 护士
                    remarks: remarks,  // 备注
                    intamount: 0,
                    deductionType: 0,     // 抵扣方式
                    deductionAmount: 0,   // 抵用金额
                    depositAmount: 0,     // 划扣储值
                    deductionTypeName: "",// 抵扣名称
                    wholeDiscount: totalDiscount,   // 整单折扣
                    lowestPriceBill: lowestPriceBill,  // 最低价格
                    dentalHygienist: treatmentUnit === "洁牙" ? $(obj).find(".doctor").val() : ""
                };
                // 判断是否欠费
                if(newArrears > 0){
                    dealInfo.arrears = parseFloat($(obj).find(".realAmount").val()) - parseFloat($("#distributionTips .distributionInput").eq(i).val());        // 欠费
                    dealInfo.serviceActualPay = parseFloat($("#distributionTips .distributionInput").eq(i).val());   // 项目实付金额
                }else {
                    dealInfo.arrears = 0;        // 欠费
                    dealInfo.serviceActualPay = parseFloat($(obj).find(".realAmount").val());   // 项目实付金额
                }
                if(parseFloat($(obj).find(".num").val()) < 1){
                    layer.msg('请输入项目数量！', {time: 1000, icon: 2});
                    return false
                }
                if ((doctor === null || doctor === "") && (nurse === null || nurse === "")) {
                    layer.msg('请选择医生或护士！', {time: 1000, icon: 2});
                    return false
                }
                billList.push(dealInfo);
            }
        }
        //  判断整单折扣是否小于 90%
        // if(parseFloat(totalDiscount) < 90){
        if(confirm("是否确定开单?")){
            $.post(Feng.ctxPath + "/consultant/getCustomerStatus/" + $("#customerId").val(), function (data) {
                if (data.split(",")[0] === '复诊') {
                    alert("复诊不能重新开单,请去进行重咨操作！");
                    return false;
                } else if (data.split(",")[1] > 0) {
                    alert("此患者还有未结账的单，不能再次开单！");
                    refundcount = 0;
                    return;
                } else if (data.split(",")[2] == 3) {
                    alert("患者TC不是当前登录人，请联系前台分配患者！");
                    return false;
                }
                else {
                    $.ajax({
                        url: Feng.ctxPath + "/consultant/openBillNew",
                        dataType: "json",
                        contentType: "application/json",
                        data: JSON.stringify(billList),
                        type: "POST",
                        success: function (data) {
                            if (data.split(",")[0] === '55') {
                                alert("前台只能开洁牙项目！")
                            } else if (data.split(",")[0] === '22') {
                                alert("此患者已不在可开单状态");
                                if (currentSeat === 'TC &gt; TC回访') {
                                    window.parent.TcRevisit.table.refresh();
                                } else if (currentSeat === 'TC &gt; TC看诊') {
                                    window.parent.Consultant.table.refresh();
                                } else if (currentSeat === 'TC &gt; 回访记录') {
                                    window.parent.ConsultantRecord.table.refresh();
                                } else if (currentSeat === 'TC &gt; 今日回访') {
                                    window.parent.ConsultantReserve.table.refresh();
                                } else if (currentSeat === 'TC &gt; 回访详情') {
                                    window.parent.ReturnVisit.table.refresh();
                                }
                                parent.layer.close(windowNameIndex);
                            } else {
                                let operationTime = data.split(",")[1];
                                let index = layer.open({
                                    type: 2,
                                    title: '开单打印',
                                    area: ['60%', '100%'],
                                    fix: true,
                                    maxmin: true,
                                    content: Feng.ctxPath + '/consultant/singlePrint/' + customerId + "/" + operationTime,
                                    success: function () {
                                        if($("#detail").val()=='isArrive'){
                                            location.href = Feng.ctxPath + '/consultantDetails/consultantToDetailByTab/' + customerId + '/2/0';
                                        }else{
                                            location.href = Feng.ctxPath + '/consultantDetails/consultantToDetailByTab/' + customerId + '/3/0';
                                        }
                                        window.parent.Consultant.table.refresh();
                                    }
                                })
                            }
                        }
                    });
                }
            },'json').fail(function(xhr,errorText,errorType){
                Feng.alert('没有权限，请联系管理员!');
            });
        }
        // }
    }
    else {
        Feng.alert("不允许操作以前的数据,需要前台重咨,要计算门诊人数！");
        count = 0;
        return false;
    }
};
//  开单操作
IsDealInfoDlg.openBillNews = function () {
    let newArrears = $("#newArrears").val(); // 欠费
    // 判断是否欠费
    if( newArrears > 0 ){
        let proDealInfo = $(".proDealInfo");    // 未使用积分储值项目集合
        let deductionDealList = $(".deductionDealList");    // 使用积分储值项目集合
        // 判断是否选择医生
        for(let i = 0 ; i < proDealInfo.length ; i ++){
            if($(proDealInfo[i]).find('.doctor').val() === ""){
                layer.msg('请选择医生！', {time: 1000, icon: 2});
                return false;
            }
        }
        $("#distribution-content-box").html("");
        // 判断是否使用储值 or 返现
        if( $('#integral').is(':checked') || $('#earnest').is(':checked') ){
            distributionArrears(deductionDealList,'deductionDealList')
        }else {
            distributionArrears(proDealInfo,'proDealInfo')
        }
    }else {
        IsDealInfoDlg.tcBilling('openBillNew');
    }
};
//  欠费分配数据填充
function distributionArrears(obj,type){
    let amount; // 变动应收
    let assignedValue;  // 分配值
    let newTotalSum = parseFloat($("#newTotalSum").val());   // 应收金额
    let newPayAmount = parseFloat($("#newPayAmount").val()); // 缴费金额
    let newArrears = parseFloat($("#newArrears").val());     // 欠费金额

    $("#distribution-receivable").html(newTotalSum);
    $("#distribution-pay").html(newPayAmount);
    $("#distribution-arrears").html(newArrears);

    for(let i = 0 ; i < obj.length ; i ++){
        //  判断是否使用积分储值 取不同的值
        if(type === 'deductionDealList'){
            amount = parseFloat($(obj[i]).find('.realAmount').html());
        }else if(type === 'proDealInfo'){
            amount = parseFloat($(obj[i]).find('.amount').val());
        }
        //  判断缴费是否大于应收
        if(newPayAmount >= amount){
            assignedValue = amount;
            newPayAmount = newPayAmount - amount;
        }else {
            assignedValue = newPayAmount;
            newPayAmount = 0;
        }
        let distributionHtml = '<div class="distribution-box-item" style="display: flex;padding: 5px 0;">' +
            '<div style="flex: 2;">'+ $(obj[i]).find('.payServiceName').text() +'</div>' +
            '<div style="flex: 1;">'+ $(obj[i]).find('.doctor').val() +'</div>' +
            '<div style="flex: 1;">'+ amount +'</div>' +
            '<div style="flex: 1;text-align: center;"><input type="text" class="distributionInput" data-bb="'+amount+'" value="' + assignedValue + '" autocomplete="off" style="width: 100px;height: 24px;text-align: center;" oninput="decimalNum(this)"></div>' +
            '</div>';
        $("#distribution-content-box").append(distributionHtml);
    }

    layer.open({
        type: 1,
        skin: 'layui-layer-demo', //样式类名
        area: ['50%', '55%'],
        fix: true,
        content: $("#distributionTips").html()
    });
}
//  欠费分配提交
function distributionSubmit(obj){
    let distributionPay = $("#distribution-pay").html();
    let totalSum = 0;
    let flag = true;
    $(obj).parent().siblings('.distribution-content').find('.distributionInput').each(function (index, obj) {
        $("#distributionTips .distributionInput").eq(index).val(parseFloat($(obj).val()));
        var bb=  $(obj).data("bb");
        if(isNaN(parseFloat($(obj).val()))){
            alert("分配金额不能为空，请填写数字")
            flag = false;
            return false;
        }
        if(parseFloat($(obj).val())>bb){
            alert("分配金额不能大于应收金额，请重新分配")
            flag = false;
            return false;
        }
        totalSum += parseFloat($(obj).val());
    });
    if(flag){
        if (parseFloat(totalSum) > parseFloat(distributionPay)) {
            Feng.alert("分配金额不应大于缴费！");
            return false;
        }
        if (parseFloat(totalSum) < parseFloat(distributionPay)) {
            Feng.alert("缴费金额为："+ distributionPay + "，目前分配总额为：" + totalSum );
            return false;
        }
        IsDealInfoDlg.tcBilling('distribution');
    }
}

$(function () {
    Feng.initValidator("isDealInfoForm", IsDealInfoDlg.validateFields);
    IsDealInfoDlg.initData();
    var radios = document.getElementsByName('radio');
    for (var i = 0; i < radios.length; i++) {
        radios[i].indexs = i + 1;
        radios[i].onchange = function () {
            document.getElementById('url1').value = '';
            if (this.checked) {
                document.getElementById("url2").style.display = "none";
                document.getElementById("url1").style.display = "none";
                document.getElementById('url1').selectedIndex = "";
                document.getElementById('url2').value = '';
                document.getElementById("url" + this.indexs).style.display = "block";
            }
        };
    }
});